import base64
import os
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QFormLayout, QLineEdit, \
    QPushButton, QFileDialog, QMessageBox, QLabel, QDialog, QInputDialog
from configparser import ConfigParser
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtCore import QByteArray

from config import init_config
from java_util import JavaUtil
from redis_util import RedisUtil
from welcome import WelcomePage


# This is the main window of the Viheating middle layer program.
class Dbmidder(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.config = ConfigParser()
        self.currentFile = 'config.ini'

        base64_image = "AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAABENz//RDlG/1RGVf9RSVD/RkBG/0E5P/8+KSf/Nh4g/yoUGf8mCw//KgsN/y8NDv8zEBL/Nxcb/z4mKv9GLjL/TTY6/1tDSv9lTlX/cFhf/3ReaP9gTFH/WkRG/3liZ/99Z2v/hm9z/3pkZ/9cPzP/aEpQ/3VVTv90UD7/ck8+/0BBY/89MlD/SD1d/11eiP9daZz/bHKh/3Ntlf9cTmj/WkdM/0g2Pf9TQET/SzY6/0AtM/84KC//KxQX/ysSFf8kEBT/Jg0Q/yoPE/8tFRn/OCEl/0ItMP9GMDP/SzY4/085O/9WP0P/W0VL/1A8QP9UTV7/ZkxP/3BPTP9sT0X/MihI/z9Bd/9gZ6L/bHa0/2d+u/9phMb/anGr/1A/Tf9VLzL/VjtB/0EuMf82Iib/Rjo4/2Fgb/9hVWT/X01V/042Ov9POj//Qy4z/zokKf8xGx//KBIW/yoUGv8sFg//MxYM/zIaEf8zHBj/OyIf/zwnI/85KCL/SSgs/00xNP9DVI//VnW2/0tcj/9UWnf/RjtP/0xGYv9LPkT/SjMz/1AuNP9jNz7/Nx8c/x4RFv82Lkb/WlB5/2BUf/9gV4D/ZWOU/0E1P/9MNzb/Szc5/1lER/9YQ0b/VkFD/00/UP9HOUn/SDAt/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4JURf+dbGD/jlJG/45VSf+WX1P/nHJw/6GJlv+krsn/jK/e/2N7tv+Emb3/oKay/5B3av+NaFP/i2pi/4lbTv+BT0H/eFJC/3NRQ/95hqb/wOL2/z9fp/9bRlP/aEZK/3BOQv9nRjH/aUwm/2hOJf9lRif/ZkIv/2VCM/9oRTb/bUw7/3xaS/9wSDb/d04+/3dRQ/9+W0n/g15U/5BnZv+UfIP/j3h5/4pvaP9+XEb/fFhF/39dTf+joKX/e2BU/2tIOf9qRjP/gG1t/3V8l/9CaLL/QUZx/1w+QP9hNz//Xjc1/2E/MP9kRC3/XUIc/1tBGf9cPx//ZkQy/1o6Jf9eOyz/YT0z/2U+Nv9uVFL/dWFe/2pHNP9vTTz/cVA+/3VPQP9zTj3/ck8//3JQQv9vTT3/bkw7/3hZSP9tTTb/ZUUt/2I9K/98Z2X/gXeH/zQvQ/9HOT7/VzYy/1s2Kv9cNTT/XDkt/1g3JP9UOBb/VDgR/1Y5Ev9aPBv/VDcS/1QzH/9bNi7/YTY9/2U8RP9kQDz/YT8t/2JEJ/9lRyj/aUow/2pLMP9pSTD/aUkv/2ZIJ/9jRyL/YkUg/2BFHv9dQxr/XUAh/10+I/9dOyn/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
        image_data = base64.b64decode(base64_image)
        self.pixmap = QPixmap()
        self.pixmap.loadFromData(QByteArray(image_data))
        icon = QIcon(self.pixmap)
        self.setWindowIcon(icon)

    def initUI(self):
        centralWidget = QWidget(self)
        self.setWindowTitle('Viheating 中间层启动 by hc')
        self.setGeometry(100, 100, 600, 400)

        self.setCentralWidget(centralWidget)

        self.layout = QVBoxLayout()
        centralWidget.setLayout(self.layout)

        self.formLayout = QFormLayout()
        self.layout.addLayout(self.formLayout)

        # 创建水平布局用于按钮
        self.buttonLayout = QHBoxLayout()

        self.layout.addLayout(self.buttonLayout)

        self.createButton = QPushButton('新建项目配置', self)
        self.createButton.clicked.connect(self.create_config)
        self.buttonLayout.addWidget(self.createButton)
        self.createButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.openButton = QPushButton('打开项目配置', self)
        self.openButton.clicked.connect(self.openFile)
        self.buttonLayout.addWidget(self.openButton)
        self.openButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")

    def create_config(self):
        filepath, ok = QInputDialog.getText(None, "输入项目名称", "项目名称")
        if ok:
            filepath = filepath + ".ini"
            if os.path.exists(filepath):
                QMessageBox.warning(self, "文件已存在", "输入的项目文件已存在")
                self.create_config()
            else:
                self.currentFile = filepath
                init_config(self.currentFile)
                QMessageBox.information(self, "Create new config.ini", "Create new config file  successfully")

    def openFile(self):

        fileName, _ = QFileDialog.getOpenFileName(self, "打开项目配置", "", "Config Files (*.ini);;All Files (*)"
                                                  )
        if fileName:
            self.config.read(fileName)
            self.currentFile = fileName
            print(os.path.abspath(fileName), self.currentFile)
            self.populateFields()
            self.checkAndAddSaveButton()

    def populateFields(self):
        self.clearForm()
        sections = self.config.sections()
        self.fields = {}

        for section in sections:
            for key, value in self.config.items(section):
                field = QLineEdit(self)
                field.setText(value)
                self.formLayout.addRow(f"{section}.{key}", field)
                self.fields[(section, key)] = field

    def checkAndAddSaveButton(self):

        self.clearButton()
        self.openButton = QPushButton('打开项目配置', self)
        self.openButton.clicked.connect(self.openFile)
        self.buttonLayout.addWidget(self.openButton)
        self.openButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        # 如果没有保存按钮，则创建并添加
        self.saveButton = QPushButton('保存配置', self)
        self.saveButton.clicked.connect(self.saveFile)
        self.buttonLayout.addWidget(self.saveButton)

        self.nextButton = QPushButton('下一步', self)
        self.nextButton.clicked.connect(self.next)
        self.buttonLayout.addWidget(self.nextButton)
        self.saveButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.nextButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")

    def clearForm(self):
        while self.formLayout.count():
            child = self.formLayout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

    def clearButton(self):
        while self.buttonLayout.count():
            child = self.buttonLayout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

    def saveFile(self):
        if self.currentFile:
            for (section, key), field in self.fields.items():
                self.config.set(section, key, field.text())
            with open(self.currentFile, 'w') as configfile:
                self.config.write(configfile)
            QMessageBox.information(self, "保存配置", "Config file saved successfully")

    def next(self):
        self.clearForm()
        self.clearButton()
        # check redis connection
        r_btn = QPushButton('Test Redis Connection', self)
        r_btn.clicked.connect(self.redis_test)
        self.r_val = QLineEdit(self)
        self.r_val.setText('status: ')
        self.r_val.setReadOnly(True)
        self.formLayout.addRow(f"redis.status", r_btn)
        self.formLayout.addRow(f"redis.status", self.r_val)

        self.r_start = QPushButton('Start Redis Server', self)
        self.r_start.clicked.connect(self.redis_start)
        self.r_start_label = QLabel('start.redis')
        self.formLayout.addRow(self.r_start_label, self.r_start)
        self.r_start.setEnabled(False)

        # check java process
        self.j_btn = QPushButton('Test Java Process', self)
        self.j_btn.clicked.connect(self.java_test)
        self.j_label = QLabel('java.status')
        self.j_val = QLineEdit(self)
        self.j_val.setText('status: ')
        self.j_val.setReadOnly(True)
        self.formLayout.addRow('java.status', self.j_btn)
        self.formLayout.addRow(self.j_label, self.j_val)
        self.j_btn.setEnabled(False)
        self.j_start = QPushButton('Start Java Process', self)
        self.j_start.clicked.connect(self.java_start)
        self.j_start_label = QLabel('start.java')
        self.formLayout.addRow(self.j_start_label, self.j_start)
        self.j_start.setEnabled(False)
        ### add open button
        self.openButton = QPushButton('打开项目配置', self)
        self.openButton.clicked.connect(self.openFile)
        self.buttonLayout.addWidget(self.openButton)
        self.openButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        ### add exit button
        self.buttonLayout.addWidget(self.openButton)
        self.exitButton = QPushButton('退出', self)
        self.exitButton.clicked.connect(self.exit)
        self.exitButton.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.buttonLayout.addWidget(self.exitButton)

        # 设置鼠标悬停提示
        r_btn.setToolTip('test redis connection')
        self.j_btn.setToolTip('test java process')
        self.r_start.setToolTip('start redis server')
        self.j_start.setToolTip('start java process')

        r_btn.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.j_btn.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.r_start.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")
        self.j_start.setStyleSheet("""QPushButton:hover {background-color: lightblue}""")

    def redis_test(self):
        redis = RedisUtil(self.currentFile)
        if redis.test_redis_connection():
            print(redis.test_redis_connection())
            self.r_val.setText('status: ok')
            self.r_val.setStyleSheet("color: green")
            self.j_btn.setEnabled(True)
            QMessageBox.information(self, "redis connection test", "redis connection test ok")

        else:
            self.r_val.setText('status: failed')
            self.r_val.setStyleSheet("color: red")
            self.r_start.setEnabled(True)
            QMessageBox.warning(self, "redis connection test",
                                "redis connection test failed, please start redis server")
        print(self.r_val.text())

    def redis_start(self):
        redis = RedisUtil(self.currentFile)
        if redis.start_redis_server():
            self.r_val.setText('status: ok')
            self.r_val.setStyleSheet("color: green")
            self.r_start.setEnabled(False)
            self.j_btn.setEnabled(True)
            QMessageBox.information(self, "redis connection test", "redis connection test ok")

        else:
            self.r_val.setText('status: failed')
            self.r_val.setStyleSheet("color: red")
            QMessageBox.warning(self, "redis connection test",
                                "redis connection test failed, please start redis server")

    def java_test(self):
        java_process = JavaUtil(self.currentFile)
        if java_process.check_port():
            print(java_process.check_port())
            self.j_val.setText('status: ok')
            self.j_val.setStyleSheet("color: green")
            self.j_start.setEnabled(False)
            QMessageBox.information(self, "java process test", "java process test ok")

        else:
            self.j_val.setText('status: failed')
            self.j_val.setStyleSheet("color: red")
            self.j_start.setEnabled(True)
            QMessageBox.warning(self, "java process test",
                                "java process test failed, please start java process")

    def java_start(self):
        java_process = JavaUtil(self.currentFile)
        if java_process.start_java():
            self.j_val.setText('status: ok')
            self.j_val.setStyleSheet("color: green")
            self.j_start.deleteLater()
            self.j_start_label.setEnabled(False)
            QMessageBox.information(self, "java process test", "java process test ok")
        else:
            self.j_val.setText('status: failed')
            self.j_val.setStyleSheet("color: red")
            QMessageBox.warning(self, "java process test",
                                "java process test failed, please start java process")

    def exit(self):
        res = QMessageBox.question(self, "退出", "是否确认退出?",
                                   QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                                   QMessageBox.StandardButton.No)

        if res == QMessageBox.StandardButton.Yes:
            self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # welcome_dialog = WelcomePage()

    dbaction = Dbmidder()
    # dbaction.setCentralWidget(welcome_dialog)
    dbaction.show()
    sys.exit(app.exec())
